﻿using Daemon.Common;
using Daemon.Data.Infrastructure.Configuration;
using Daemon.Data.Substructure.Enums;
using Daemon.Repository.EF;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace DaemonAPI.Controllers.V1
{
    [ApiController]
    [Route("daemonApi/[controller]/[action]")]
    public class SessionItemController : ControllerBase
    {
        private readonly SessionItemRepository _sessionItemRepository;

        private readonly IContextInfoProvider _contextInfoProvider;

        public SessionItemController(SessionItemRepository sessionItemRepository, IContextInfoProvider contextInfoProvider)
        {
            _sessionItemRepository = sessionItemRepository;
            _contextInfoProvider = contextInfoProvider;
        }

        /// <summary>
        /// Create or update <see cref="SessionItem"/>.
        /// </summary>
        /// <param name="sessionItem">The <see cref="SessionItem"/></param>
        /// <returns>The registered <see cref="SessionItem"/> with a given Id and updated live time</returns>
        [Route("")]
        [HttpPut]
        public ResultModel<SessionItem> Put([FromBody] SessionItem sessionItem)
        {
            var prefix = _contextInfoProvider.Prefix;
            sessionItem = string.IsNullOrEmpty(sessionItem.Id) ? _sessionItemRepository.Register(sessionItem, prefix) : _sessionItemRepository.Update(sessionItem, prefix);
            return new ResultModel<SessionItem>(sessionItem);
        }

        /// <summary>
        /// Log off
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("{id}")]
        [HttpDelete]
        public ResultModel<bool> LogOff([FromQuery] string id)
        {
            return new ResultModel<bool>(_sessionItemRepository.Delete(id, LogoutReasonEnum.UserInitiatedLogout));
        }
    }
}